﻿using Common;
using NB.MGJ.Common.Helper;
using NB.MGJ.Common.MVC;
using NB.MGJ.Model;
using NB.MGJ.Service.Config;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;

namespace NB.MGJ.Web.Controllers
{
    /// <summary>
    /// 微信管理
    /// 负责人 Dy
    /// 2017-10-17
    /// </summary>
    public class ConfigManagerController : BaseController
    {
        ConfigManagerService _wxService = new ConfigManagerService();
                   JsonHelper jsonHelper = new JsonHelper();

        #region 视图
        public ActionResult WXBing()
        {
            return View();
        }

        /// <summary>
        /// 微信帮助视图
        /// </summary>
        /// <returns></returns>
        public ActionResult WXHelp() 
        {
            return View();
        }
        /// <summary>
        /// 短信信息绑定
        /// </summary>
        /// <returns></returns>
        public ActionResult SMSApiBind()
        {
           
            return View();
        }
         /// <summary>
         /// 短信帮助视图
         /// </summary>
         /// <returns></returns>
        public ActionResult SMSHelp() 
        {
            return View();
        }
        /// <summary>
        /// 公众号信息帮助视图
        /// </summary>
        /// <returns></returns>
        public ActionResult PublicHelp()
        {
            return View();
        }
        /// <summary>
        /// 商户信息帮助视图
        /// </summary>
        /// <returns></returns>
        public ActionResult UserHelp()
        {
            return View();
        }

        public ActionResult PhoneVerify() 
        {
            return View();
        }
        #endregion

        #region    公众号绑定

        /// <summary>
        /// 绑定 微信App信息
        /// </summary>
        /// <returns></returns>
        public int AppSave(HttpPostedFileBase file, string submitData,string Type) 
        {
          
            config_WX wxModel = jsonHelper.JSONToObject<config_WX>(submitData);
           int id=_wxService.getWXBind_id(LogOnUser.EnterpriseId);
           string paths = "";
           string filePath = "";
           string fileName = string.Empty;
           string destPath = AppConst.certFile;
           if (Type == "app")
           {
               wxModel.AppState = 1;
           }
           else
           {
               wxModel.InfoState = 1;
           }
           if (file != null)
           {
               if (file.ContentLength > 0 && file.ContentLength != 945)
               {
                   
                   string fileNames = System.IO.Path.GetFileName(file.FileName);
                   string name =LogOnUser.EnterpriseName;
                   if (!Directory.Exists(Server.MapPath(destPath)))
                   {
                       Directory.CreateDirectory(Server.MapPath(destPath));
                   }
                   fileName = destPath + name.Replace(" ","").Replace("/","")  + fileNames;
                   filePath = fileName;
                   paths = Server.MapPath(fileName);
                   file.SaveAs(paths);
                   
               }
           }
          
            if (id>0)//修改
            {
               
                wxModel.ID = id;
                wxModel.ChangeDate = DateTime.Now;
                wxModel.ChangeLoginID = LogOnUser.UserID;
                wxModel.ChangeLoginName = LogOnUser.LoginName;
                wxModel.CredentialAddress = filePath;
              return  _wxService.UpdWXBing(wxModel);
            }
            else//添加数据
            {
                wxModel.Eid = LogOnUser.EnterpriseId;
                wxModel.ChangeDate = DateTime.Now;
                wxModel.ChangeLoginID = LogOnUser.UserID;
                wxModel.ChangeLoginName = LogOnUser.LoginName;
                wxModel.CredentialAddress = filePath;
                return _wxService.WXBindAdd(wxModel);
            }
         
        }

        #region 数据显示
        /// <summary>
        /// 绑定
        /// </summary>
        /// <returns></returns>
        public JsonResult BindLoad()
        {
             //return Json(_wxService.GetwxBindModel(LogOnUser.EnterpriseId),JsonRequestBehavior.AllowGet);
            object model = _wxService.GetwxBindModel(LogOnUser.EnterpriseId);
             
            return Json(model==null?"0":model, JsonRequestBehavior.AllowGet);
        }

        #endregion

        #endregion

        #region 短息接口配置

        /// <summary>
        /// 获取短信的model
        /// </summary>
        /// <returns></returns>
        public JsonResult SMSApiModel()
        {
        var model=_wxService.GetSMSApiModel(LogOnUser.EnterpriseId);
        if (model == null) return Json("");
        return Json(model);
        }

        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool SMSApiSave(config_SMS model)
        {
            model.Name = "聚合短信接口平台";
            if(model==null)return false;
            int i=0;
            if(model.ID==0)
            {
            model.CreateBy=LogOnUser.UserID;
            model.CreateByName=LogOnUser.RealName;
            model.EnterpriseId=LogOnUser.EnterpriseId;
            model.CreateOn=DateTime.Now;
            model.ViewDel=0;
            model.Type=1;//验证码
            model.state=1;//验证通过
            i= _wxService.AddSMSApi(model);
             }
            else
            {
                model.state = 1;//验证通过
                model.ChangeBy = LogOnUser.UserID;
                model.ChangeByName = LogOnUser.RealName;
                model.ChangeOn = DateTime.Now;
              i=  _wxService.UpdateSMSApi(model);
            }
            if (i <= 0) return false;
            else return true;
        }

        public string GetSMS(string phoneNum,string key,string code) 
        {
            SMSApi sms = new SMSApi();
            string RealName = LogOnUser.RealName == "" || LogOnUser.RealName == null ? LogOnUser.LoginName : LogOnUser.RealName;
            string reulst = sms.SendSMSApi(key, phoneNum, code, LogOnUser.RealName);
            return reulst;
        }

        #endregion


        #region 验证

        /// <summary>  
        /// 验证APPid      APPsecret
        /// </summary>  
        /// <returns></returns>  
        public JObject GetAccessToken(string appid, string secret)
        {

            string grant_type = "client_credential";
            string tokenUrl = string.Format("https://api.weixin.qq.com/cgi-bin/token?grant_type={0}&appid={1}&secret={2}", grant_type, appid, secret);
            var wc = new WebClient();
            var strReturn = wc.DownloadString(tokenUrl);
            return JObject.Parse(strReturn);
        }

        public string Verify(string Appid, string AppSecret) 
        {
          string str=  GetAccessToken(Appid, AppSecret).ToString();
          return str;
        }
        #endregion

    }
}